//
//  ClientWebViewController.m
//  YYZB
//
//  Created by 顾悦 on 16/4/5.
//
//

#import "ClientWebViewController.h"

#import "ClientLoginViewController.h"

#import "WXApiRequestHandler.h"
#import "WXApiManager.h"

#import "AppConfiguration.h"

static NSString * webViewMessageNameNeedLogin = @"needLogin";
static NSString * webViewMessageNameKeepState = @"keepState";
static NSString * webViewMessageNameCurrentLocation = @"curLocation";
static NSString * webViewMessageNameSetDefaultAddress = @"setDefaultAddress";

static NSString * webViewMessageNameStartWeChatPayment = @"startWeChatPayment";
static NSString * webViewMessageNameGotoMyOrders = @"gotoMyOrders";

@interface ClientWebViewController ()

@end

@implementation ClientWebViewController

- (NSString *)baseURL {
//    return @"http://testyyzbhc.einwin.com/pages/";
    return @"http://yyzbhc.einwin.com/pages/";
    
    
    
    
//    return [AppConfiguration isProductionEnv] ? @"http://yyzbhc.einwin.com/pages/" : @"http://xtyyzb.einwin.com:82/pages/";
//    return @"http://10.129.100.55:9000/pages/";
//    return @"http://115.29.179.142:4004/YYZB/HTML_CLIENT/pages/";
//    return @"http://10.129.101.57:8081/pages/";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:webViewMessageNameNeedLogin];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:webViewMessageNameKeepState];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:webViewMessageNameCurrentLocation];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:webViewMessageNameSetDefaultAddress];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:webViewMessageNameStartWeChatPayment];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:webViewMessageNameGotoMyOrders];
    
    
//    修改CommunityId为空的bug 方法有点粗暴
//    NSString *source = [NSString stringWithFormat:@"setCurLocation('{\"CityId\" : \"%@\", \"CityName\" : \"%@\", \"CommunityId\" : \"%@\", \"CommunityName\" : \"%@\"}');", [UserInfoController defaultCityID], [UserInfoController defaultCityName], [UserInfoController defaultCommunityID], [UserInfoController defaultCommunityName]];
//    WKUserScript *script = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
//    [self.webView.configuration.userContentController addUserScript:script];
}

- (void)viewDidAppear:(BOOL)animated {
    
    if (self.keepState && !self.isMovingToParentViewController) {
        return;
    }

    [super viewDidAppear:animated];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    if (self.presentedViewController) {
        self.keepState = YES;
    }/* else {
        self.keepState = NO;
    }*/
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    [super userContentController:userContentController didReceiveScriptMessage:message];
    if ([message.name isEqualToString:webViewMessageNameNeedLogin]) {
        UINavigationController *nav = self.navigationController;
        NSArray *vcs = nav.viewControllers;
        UIViewController *vc = self;
        if (vcs.count >= 2) {
            vc = vcs[vcs.count - 2];
        }
        [self.navigationController popViewControllerAnimated:NO];
        ClientLoginViewController *loginViewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"ClientLoginViewController"];
        loginViewController.completionHandler = ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [vc.navigationController popViewControllerAnimated:YES];
            });
        };
        [vc.navigationController pushViewController:loginViewController animated:NO];
    }
    else if ([message.name isEqualToString:webViewMessageNameKeepState]) {
        self.keepState = [message.body boolValue];
    }
    else if ([message.name isEqualToString:webViewMessageNameCurrentLocation]) {
        NSString *js = [NSString stringWithFormat:@"setCurLocation('{\"CityId\" : \"%@\", \"CityName\" : \"%@\", \"CommunityId\" : \"%@\", \"CommunityName\" : \"%@\"}');", [UserInfoController defaultCityID], [UserInfoController defaultCityName], [UserInfoController defaultCommunityID], [UserInfoController defaultCommunityName]];
        [self.webView evaluateJavaScript:js completionHandler:^(id _Nullable r, NSError * _Nullable error) {
            
        }];
    }
    else if ([message.name isEqualToString:webViewMessageNameSetDefaultAddress]) {
        id body = message.body;
        NSDictionary *bd;
        if ([body isKindOfClass:[NSDictionary class]]) {
            bd = body;
        } else if ([body isKindOfClass:[NSString class]]) {
            bd = [NSJSONSerialization JSONObjectWithData:[body dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
        }
        bd = [NSDictionaryNullKiller dataByReplacingNullWithEmptyString:bd];
    }
    else if ([message.name isEqualToString:webViewMessageNameStartWeChatPayment]) {
        id body = message.body;
        NSDictionary *bd;
        if ([body isKindOfClass:[NSDictionary class]]) {
            bd = body;
        } else if ([body isKindOfClass:[NSString class]]) {
            bd = [NSJSONSerialization JSONObjectWithData:[body dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
        }
        bd = [NSDictionaryNullKiller dataByReplacingNullWithEmptyString:bd];
        [self bizPay:bd];
    }
    else if ([message.name isEqualToString:webViewMessageNameGotoMyOrders]) {
        if ([message.body integerValue] == 0) {
            self.tabBarController.selectedIndex = 1;
        } else {
            self.tabBarController.selectedIndex = 0;
        }
        [self.navigationController popToRootViewControllerAnimated:NO];
    }
}

- (void)bizPay:(NSDictionary *)bd {
    NSString *res = [WXApiRequestHandler jumpToBizPay:bd];
    if( ![@"" isEqual:res] ){
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"支付失败" message:res delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        
        [alter show];
    }
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
